

package cn.shengchao.examstart.user.acl.adapters.repositories;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.shengchao.examstart.user.acl.ports.repositories.IDeptRepository;
import cn.shengchao.examstart.user.domain.entity.Dept;
import cn.shengchao.examstart.user.infrastructure.dao.DeptDao;
import cn.shengchao.examstart.user.infrastructure.dao.po.TDept;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class DeptRepository implements IDeptRepository {

    @Autowired
    private DeptDao deptDao;
    @Transactional
    @Override
    public Dept createNewDept(Dept dept) {
        TDept tDept = new TDept();
        while (deptDao.exists(Wrappers.lambdaQuery(TDept.class).eq(TDept::getName, dept.getName()))){
            dept.setName(dept.getName()+ RandomUtil.randomInt(1000,9999));
        }
        BeanUtil.copyProperties(dept, tDept);
        tDept.setId(null);
        tDept.setCreateUser(1L);
        deptDao.insert(tDept);
        return BeanUtil.copyProperties(tDept, Dept.class);
    }

    @Override
    public Dept getDeptById(Long deptId) {
        TDept tDept = deptDao.selectById(deptId);
        return BeanUtil.copyProperties(tDept, Dept.class);
    }
}
